<?php

class logger {

    private $data_model;
    const WARNING = 'WARNING';
    const ERROR = 'ERROR';
    const INFO = 'INFO';

    protected function __construct() {
        $this->data_model = new log_m_core();
    }

    public static function i() {
        static $logger = NULL;
        if ($logger === NULL) {
            $logger = new logger();
        }
        return $logger;
    }
    private function __format_msg($msg){
        if(is_object($msg) || is_array($msg) || is_a($msg, "IteratorAggregate")){
            return print_r($msg,TRUE);
        }else{
            return $msg;
        }
    }
    private function __not_self(){
        return get_instance()->router->class !== "sys_log_viewer";
    }
    public function warning($msg, $group='', $module=NULL) {
        if ($this->__not_self()) {
            $trace = debug_backtrace();
            $this->write($this->__format_msg($msg), @$trace[1]['class'], @$trace[0]['file'], @$trace[1]['function'], @$trace[0]['line'], self::WARNING, $group, $module);
        }
    }

    public function error($msg, $group='', $module=NULL) {
        if ($this->__not_self()) {
            $trace = debug_backtrace();
            $this->write($this->__format_msg($msg), @$trace[1]['class'], @$trace[0]['file'], @$trace[1]['function'], @$trace[0]['line'], self::ERROR, $group, $module);
        }
    }

    public function info($msg, $group='', $module=NULL) {
        if ($this->__not_self()) {
            $trace = debug_backtrace();
            $this->write($this->__format_msg($msg), @$trace[1]['class'], @$trace[0]['file'], @$trace[1]['function'], @$trace[0]['line'], self::INFO, $group, $module);
        }
    }

    private function write($msg, $class, $file, $func, $line, $type, $group='', $module=NULL) {
        $this->data_model->insert($module ? $module : current_module(), $msg, $class, $file, $func, $line, $type, $group);
    }

    public function get_log_data($start, $num_of_records, $criteria=array()) {
        $return['data'] = $this->data_model->get_data($start, $num_of_records, $criteria);
        $return['count'] = $this->data_model->count_rows($criteria);
        return $return;
    }

    public function clear() {
        return $this->data_model->delete_log();
    }

    public function clear_where($criteria) {
        return $this->data_model->delete_log($criteria);
    }

}

?>